package com.utc.cards.table.jade.agent.rulesAgent;

import jade.core.AID;
import jade.core.behaviours.OneShotBehaviour;
import jade.lang.acl.ACLMessage;

import java.util.Map.Entry;
import java.util.Stack;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.utc.cards.common.jade.Mapper;
import com.utc.cards.model.HostModel;
import com.utc.cards.model.deck.Deck;
import com.utc.cards.model.game.Fold;
import com.utc.cards.model.game.IRules;
import com.utc.cards.model.game.Info;
import com.utc.cards.model.game.InfoType;

public class CalculScoreBehaviour extends OneShotBehaviour
{

    private static Logger log = LoggerFactory.getLogger(CalculScoreBehaviour.class);
    private static final long serialVersionUID = 4280298792939434749L;

    private RulesAgent agent;
    private HostModel model;

    public CalculScoreBehaviour(RulesAgent rulesAgent)
    {
        super(rulesAgent);
        this.agent = rulesAgent;
        this.model = agent.getModel();
    }

    @Override
    public void action()
    {
        log.info("Sending Scores in broadcast ...");
        IRules rules = model.getGame().getRules();
        Stack<Fold> plisFini = model.getOldFolds();
        Deck deck = model.getGame().getDeck();
        rules.calculScore(deck, plisFini, model.getGame().getPlayers());

        ACLMessage message = new ACLMessage(ACLMessage.INFORM);
        for (Entry<String, AID> entry : model.getPlayersMap().entrySet())
        {
            message.addReceiver(entry.getValue());
        }
        try
        {
            Info info = new Info(InfoType.SCORE, Mapper.getObjectMapper().writeValueAsString(model.getScores()));
            message.setContent(Mapper.getObjectMapper().writeValueAsString(info));
            agent.send(message);
            log.info("Sending Scores in broadcast DONE");
        }
        catch (JsonProcessingException e)
        {
            log.error("Error while mapping Score");
            e.printStackTrace();
        }
    }
}
